package com.example.hlddz2.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.hlddz2.R;
import com.example.hlddz2.model.Order;
import com.example.hlddz2.repository.OrderRepository;
import java.util.ArrayList;
import java.util.List;

public class OrderListActivity extends AppCompatActivity {
    private RecyclerView rvOrders;
    private OrderAdapter adapter;
    private List<Order> orderList = new ArrayList<>();
    private int orderType;
    private static OrderRepository orderRepository;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_list);

        orderType = getIntent().getIntExtra("orderType", 0);
        orderRepository = OrderRepository.getInstance(this);
        initTitle();
        initRecyclerView();
        loadOrders(); // 加载订单数据
    }

    private void initTitle() {
        TextView tvTitle = findViewById(R.id.tv_title);
        String[] titles = {"全部订单", "待付款", "待发货", "待收货", "待评价"};
        tvTitle.setText(titles[orderType]);
    }

    private void initRecyclerView() {
        rvOrders = findViewById(R.id.rv_orders);
        rvOrders.setLayoutManager(new LinearLayoutManager(this));

        adapter = new OrderAdapter(orderList, new OrderAdapter.OnActionClickListener() {
            @Override
            public void onActionClick(Order order, String action) {
                handleOrderAction(order, action);
            }

            @Override
            public void onDeleteOrder(Order order) {
                deleteOrder(order);
            }
        });

        rvOrders.setAdapter(adapter);
    }
    private void deleteOrder(Order order) {
        List<Order> orders = orderRepository.getOrders().getValue();
        if (orders != null) {
            // 查找并移除订单
            boolean removed = orders.removeIf(o -> {
                // 避免空指针，先判断订单号是否存在
                if (o.getOrderNo() == null || order.getOrderNo() == null) {
                    return false;
                }
                return o.getOrderNo().equals(order.getOrderNo());
            });

            if (removed) {
                orderRepository.saveOrders(orders); // 保存更新后的订单列表
                Toast.makeText(this, "订单已删除", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 加载订单并根据类型过滤
    private void loadOrders() {
        orderRepository.getOrders().observe(this, orders -> {
            List<Order> filteredOrders = new ArrayList<>();
            for (Order order : orders) {
                if (orderType == 0) { // 全部订单
                    filteredOrders.add(order);
                } else if (orderType == 1 && "待付款".equals(order.getStatus())) {
                    filteredOrders.add(order);
                } else if (orderType == 2 && "待发货".equals(order.getStatus())) {
                    filteredOrders.add(order);
                } else if (orderType == 3 && "待收货".equals(order.getStatus())) {
                    filteredOrders.add(order);
                } else if (orderType == 4 && "待评价".equals(order.getStatus())) {
                    filteredOrders.add(order);
                }
            }
            orderList.clear();
            orderList.addAll(filteredOrders);
            adapter.notifyDataSetChanged();
        });
    }
    private void handleOrderAction(Order order, String action) {
        switch (action) {
            case "付款":
                order.setStatus("待发货");
                updateOrder(order);
                Toast.makeText(this, "订单" + order.getOrderNo() + "付款成功", Toast.LENGTH_SHORT).show();
                break;
            case "提醒发货":
                order.setStatus("待收货");
                Toast.makeText(this, "已提醒商家尽快发货", Toast.LENGTH_SHORT).show();
                updateOrder(order);
                break;
            case "确认收货":
                order.setStatus("待评价");
                updateOrder(order);
                Toast.makeText(this, "订单" + order.getOrderNo() + "已确认收货", Toast.LENGTH_SHORT).show();
                break;
            case "去评价":
                // 这里可以跳转到评价页面
                Toast.makeText(this, "跳转到评价页面", Toast.LENGTH_SHORT).show();
                // 评价完成后可以更新状态为"已完成"
                // order.setStatus("已完成");
                // updateOrder(order);
                break;
            default:
                Toast.makeText(this, "查看订单详情", Toast.LENGTH_SHORT).show();
        }
    }

    private void updateOrder(Order updatedOrder) {
        // 1. 检查更新的订单是否为空或订单号为空
        if (updatedOrder == null || updatedOrder.getOrderNo() == null) {
            Toast.makeText(this, "订单信息错误", Toast.LENGTH_SHORT).show();
            return;
        }

        List<Order> orders = orderRepository.getOrders().getValue();
        if (orders != null) {
            for (int i = 0; i < orders.size(); i++) {
                Order existingOrder = orders.get(i);
                // 2. 先判断现有订单和其订单号是否为空，再比较
                if (existingOrder != null && existingOrder.getOrderNo() != null
                        && existingOrder.getOrderNo().equals(updatedOrder.getOrderNo())) {
                    orders.set(i, updatedOrder);
                    break;
                }
            }
            orderRepository.saveOrders(orders); // 保存更新后的订单列表
        }
    }

    static class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {
        private List<Order> data;
        private OnActionClickListener listener;

        public OrderAdapter(List<Order> data, OnActionClickListener listener) {
            this.data = data;
            this.listener = listener;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = View.inflate(parent.getContext(), R.layout.item_order, null);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Order order = data.get(position);
            holder.tvOrderNo.setText("订单号：" + order.getOrderNo()); // 修正为实例方法调用

            List<Order.OrderItem> items = order.getItems();
            if (items != null && !items.isEmpty()) {
                String goodsName = items.get(0).getName();
                if (items.size() > 1) {
                    goodsName += " 等" + items.size() + "件商品";
                }
                holder.tvGoodsName.setText(goodsName);
            }

            holder.tvPrice.setText("¥" + String.format("%.2f", order.getTotalPrice()));
            holder.tvStatus.setText(order.getStatus());

            switch (order.getStatus()) {
                case "待付款":
                    holder.btnAction.setText("付款");
                    break;
                case "待发货":
                    holder.btnAction.setText("提醒发货");
                    break;
                case "待收货":
                    holder.btnAction.setText("确认收货");
                    break;
                case "待评价":
                    holder.btnAction.setText("去评价");
                    break;
                default:
                    holder.btnAction.setText("查看详情");
            }

            holder.btnAction.setOnClickListener(v ->
                    listener.onActionClick(order, holder.btnAction.getText().toString())
            );
            holder.btnDelete.setOnClickListener(v -> {
                new AlertDialog.Builder(holder.itemView.getContext())
                        .setTitle("确认删除")
                        .setMessage("确定要删除该订单吗？")
                        .setPositiveButton("删除", (dialog, which) -> {
                            // 调用删除订单方法
                            listener.onDeleteOrder(order);
                            // 这里不需要显示Toast，因为删除逻辑在Activity中实现
                            // 原有的Toast应该在Activity的deleteOrder()方法中显示
                        })
                        .setNegativeButton("取消", null)
                        .show();
            });
        }
        private void deleteOrder(Order order) {
            List<Order> orders = orderRepository.getOrders().getValue();
            if (orders != null) {
                // 查找并移除订单
                boolean removed = orders.removeIf(o -> {
                    // 避免空指针，先判断订单号是否存在
                    if (o.getOrderNo() == null || order.getOrderNo() == null) {
                        return false;
                    }
                    return o.getOrderNo().equals(order.getOrderNo());
                });

                if (removed) {
                    orderRepository.saveOrders(orders); // 保存更新后的订单列表
                }
            }
        }


        @Override
        public int getItemCount() {
            return data.size();
        }

        static class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvOrderNo, tvGoodsName, tvPrice, tvStatus, btnAction,btnDelete;

            ViewHolder(View itemView) {
                super(itemView);
                tvOrderNo = itemView.findViewById(R.id.tv_order_no);
                tvGoodsName = itemView.findViewById(R.id.tv_goods_name);
                tvPrice = itemView.findViewById(R.id.tv_price);
                tvStatus = itemView.findViewById(R.id.tv_status);
                btnAction = itemView.findViewById(R.id.btn_action);
                btnDelete = itemView.findViewById(R.id.btn_delete);
            }
        }

        interface OnActionClickListener {
            void onActionClick(Order order, String action);
            void onDeleteOrder(Order order);
        }
    }
}